<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <title>Document</title>
  </head>
  <body>
    <ul class="stu-list"></ul>
    <script>
      //JSON数据
      var students1 = [
        {
          sno: "8254025",
          name: "张三",
          age: 18,
          tel: 2131242142,
          score: [78, 90, 99],
        },
        {
          sno: "8254025",
          name: "李四",
          age: 19,
          tel: 4351242142,
          score: [98, 60, 99],
        },
        {
          sno: "8254025",
          name: "王五",
          age: 20,
          tel: 6547548754142,
          score: [68, 80, 99],
        },
        {
          sno: "8254025",
          name: "赵六",
          age: 20,
          tel: 6547548754142,
          score: [68, 80, 99],
        },
      ];
      //解析JSON(直接访问JSON存储的变量即可)
      console.log(students1);
      console.log(students1[0].name);
      console.log(students1[2].name);

      //  字符串数据必须在一行 \续行符
      var students2 =
        '[\
          {\
            "sno": "8254025",\
            "name": "玛丽亚",\
            "age": 18,\
            "tel": 2131242142,\
            "score": [78, 90, 99]\
          },\
          {\
            "sno": "8254025",\
            "name": "李字",\
            "age": 19,\
            "tel": 4351242142,\
            "score": [98, 60, 99]\
          },\
          {\
            "sno": "8254025",\
            "name": "王五",\
            "age": 20 ,\
            "tel": 6547548754142,\
            "score": [68, 80, 99]\
          }\
      ]';
      console.log(students2);
      //如果返回的是具有JSON格式的字符串，需要将它解析为JavaScript识别的JSON,用JSON.parse()这个方法实现。
      //JSON格式的字符串规范:其中的键必须用双引号引起来，值如果是字符型数据，也必须用双引号引起来。
      console.log(JSON.parse(students2)); //将JSON格式的字符串转换为JSON
      console.log(JSON.stringify(students2)); //将JSON转换为JSON格式的字符串

      //解析JSON数据的目的是为了将数动态据渲染到前端（浏览器）
      var txt = "";
      for (var i = 0; i < students1.length; i++) {
        //console.log(students1[i]);
        txt +=
          "<li>学生姓名:"+ students1[i].name + "联系方式:" + students1[i].tel + "</li>";
      } //常量用引号引起来，变量不加引号
      console.log(txt);
      document.getElementsByClassName("stu-list")[0].innerHTML = txt;
     
      var txt = "";
      var stu2 = JSON.parse(students2)  //先对字符串进行转换
      for (var i = 0; i < stu2.length; i++) {
        //console.log(students1[i]);
        txt +=
          "<li>学生姓名:"+ stu2[i].name + "联系方式:" + stu2[i].tel + "</li>";
      } //常量用引号引起来，变量不加引号
      console.log(txt);
      document.getElementsByClassName("stu-list")[0].innerHTML = txt;
    </script>
  </body>
</html>
